'use client';

import { useToast } from '@/hooks/use-toast';
import { result } from '@/lib/utils';
import { shopUpdateOrderStatus } from '@/service/actions/order';
import ConfirmButton from '../common/confirm-button';
import { Button } from '../ui/button';

export default function HandleOrderButton({
  orderId,
  status,
  variant = 'default',
}: {
  orderId: number;
  status: string;
  variant?: 'ghost' | 'outline' | 'default';
}) {
  const { toast } = useToast();
  const actionName =
    status === 'unaccepted'
      ? '接受订单'
      : status === 'pending'
        ? '开始配送'
        : status === 'delivering'
          ? '完成订单'
          : '';
  return ['unaccepted', 'pending', 'delivering'].includes(status) ? (
    <ConfirmButton
      title={actionName}
      description={`确认${actionName}吗？`}
      button={
        <Button variant={variant} className="p-2">
          {actionName}
        </Button>
      }
      onClick={async () => {
        const newStatus =
          status === 'unaccepted'
            ? 'pending'
            : status === 'pending'
              ? 'delivering'
              : 'completed';
        const { error } = await shopUpdateOrderStatus({
          orderId,
          status: newStatus,
        });
        error
          ? toast({ title: error.message, variant: 'destructive' })
          : toast({ title: '操作成功' });
        return error ? result(error, error.message) : result();
      }}
    />
  ) : null;
}
